package com.xbwang.utils;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.xbwang.pojo.TemplateInfo;
import com.xbwang.pojo.TextMessage;
import com.xbwang.pojo.TranTemplate;
import com.xbwang.pojo.WXTransportTemplate;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微信消息处理类（微信消息交互大部分就是xml格式交互）
 */
@Slf4j
public class WxMessageUtil {

    /*
     * xml转map
     */
    public static Map<String, String> xmlToMap(HttpServletRequest request) throws IOException, DocumentException {
        HashMap<String, String> map = new HashMap<String,String>();
        SAXReader reader = new SAXReader();

        InputStream ins = request.getInputStream();
        Document doc = reader.read(ins);

        Element root = doc.getRootElement();
        @SuppressWarnings("unchecked")
        List<Element> list = (List<Element>)root.elements();

        for(Element e:list){
            map.put(e.getName(), e.getText());
        }
        ins.close();
        return map;
    }

    /**
     * 获取公众号回复信息（xml格式）
     */
    public static String getWxReturnMsg(Map<String, String> decryptMap, String content) throws UnsupportedEncodingException {
        log.info("---开始封装xml---decryptMap:" + decryptMap.toString());
        TextMessage textMessage = new TextMessage();
        textMessage.setToUserName(decryptMap.get("FromUserName"));
        textMessage.setFromUserName(decryptMap.get("ToUserName"));
        textMessage.setCreateTime(System.currentTimeMillis());
        textMessage.setMsgType("text"); // 设置回复消息类型
        textMessage.setContent(content); // 设置回复内容
        String xmlMsg = getXmlString(textMessage);
        // 设置返回信息编码,防止中文乱码
//        String encodeXmlMsg = new String(xmlMsg.getBytes(), "ISO-8859-1");
        //本地编码
//        String encodeXmlMsg = new String(xmlMsg.getBytes(), "GBK");
        //线上公众号编码
        String encodeXmlMsg = new String(xmlMsg.getBytes(), "UTF-8");
        return encodeXmlMsg;
    }

    /**
     * 设置回复消息xml格式
     */
    private static String getXmlString(TextMessage textMessage) {
        String xml = "";
        if (textMessage != null) {
            xml = "<xml>";
            xml += "<ToUserName><![CDATA[";
            xml += textMessage.getToUserName();
            xml += "]]></ToUserName>";
            xml += "<FromUserName><![CDATA[";
            xml += textMessage.getFromUserName();
            xml += "]]></FromUserName>";
            xml += "<CreateTime>";
            xml += textMessage.getCreateTime();
            xml += "</CreateTime>";
            xml += "<MsgType><![CDATA[";
            xml += textMessage.getMsgType();
            xml += "]]></MsgType>";
            xml += "<Content><![CDATA[";
            xml += textMessage.getContent();
            xml += "]]></Content>";
            xml += "</xml>";
        }
        log.info("xml封装结果=>" + xml);
        return xml;
    }

    //模板消息
    public static String sendTranTemplate(WXTransportTemplate resource, String accessToken){
        //拿到accessToken
//        String accessToken = HttpUtils.access_token;
//        if (null == accessToken){
//            accessToken = HttpUtils.dogetToken();
//        }
//        System.out.println("现在取出的token是："+accessToken);

        //发送模板消息开始
        TranTemplate tranTemplate = new TranTemplate();
        //设置接收司机微信ID
        tranTemplate.setTouser(resource.getOpenid());
        //设置模板ID
        tranTemplate.setTemplate_id(resource.getTemplateId());
        //详情链接
        tranTemplate.setUrl(resource.getUrl());
        //给模板的内容赋值
        Map<String , TemplateInfo> dataMap = new HashMap<>();
        TemplateInfo first = new TemplateInfo(resource.getFirst(),"#DC143C");
        dataMap.put("first",first);
        TemplateInfo keyword1 = new TemplateInfo(resource.getKeyword1(),"#173177");
        dataMap.put("keyword1",keyword1);
        TemplateInfo keyword2 = new TemplateInfo(resource.getKeyword2(),"#173177");
        dataMap.put("keyword2",keyword2);
        TemplateInfo keyword3 = new TemplateInfo(resource.getKeyword3(),"#173177");
        dataMap.put("keyword3",keyword3);
        TemplateInfo remark = new TemplateInfo(resource.getRemark(),"#DC143C");
        dataMap.put("remark",remark);
        tranTemplate.setData(dataMap);

        JSONObject jsonObject = JSONUtil.parseObj(tranTemplate);
        //将入参转为字符串
        String jsonParam = jsonObject.toString();
        //发起请求发送模板信息
        String sendTemplateUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";
        String result = HttpUtil.requestPost(sendTemplateUrl + accessToken, jsonParam);

        return  result;
    }

}
